<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace Sun;

abstract class Controller implements IController {
    protected $def_action;

    public function __construct($def_action) {
        $this->def_action = $def_action;

        //if ($def_action === null)
        //    throw new Exception("Default action can't be empty");
    }

    public function Action($request, $name = null) {
        if ($name == null) $name = $this->def_action;
        $method = $name."Action";
        if (method_exists($this, $method)) return $this->$method($request);
        else return $this->ErrorAction($request, $name);
    }

    public function ErrorAction($request, $name) {
        $this->Action($request);
    }

    public function RenderView($view, array $data = array(),
            array $cond = array(), array $err = array()) {

        $scene = explode("/", $view);
        try {
            $v = Sun::view($scene[0]);
            if (isset($scene[1]) && !$v->FindScene($scene[1]))
                    throw new \Exception();
        } catch (\Exception $e) {
            //throw $e;
            return Sun::view("Index\\NotFound")->Render(array('tab' => "MenuEnter"));
        }

        if (isset($scene[1]))
            $v->data_scene = $scene[1];

        $v->SetData($data, $cond, $err);
        $v->Render();
    }

    public function RenderViewScene($view, array $data = array(),
            array $cond = array(), array $err = array()) {

        $scene = explode("/", $view);
        try {
            $v = Sun::view($scene[0]);
        } catch (\Exception $e) {
            throw $e;
            //return Sun::view("Index\\NotFound")->Render(array('tab' => "MenuEnter"));
        }

        $v->SetData($data, $cond, $err);
        $v->RenderScene($scene[1]);
    }
}

